package com.example.start

import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.ScaleGestureDetector
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.graphics.alpha
import androidx.core.os.EnvironmentCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.drawToBitmap
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class WatermarkActivity : AppCompatActivity() {
    private lateinit var imageUri: Uri
    private var canvas = Canvas()
    private lateinit var scaleGestureDetector: ScaleGestureDetector
    private var scaleFactor = 1.0f
    private lateinit var watermarkImageView : ImageView
    companion object {
        private const val REQUEST_SELECT_IMAGE = 100
        private const val REQUEST_CAMERA = 101
        private const val REQUEST_FOLDER = 102
        private const val CAMERA_PERMISSION_CODE = 213
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_watermark)
        supportActionBar?.title = "水印"
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        var actionBar = supportActionBar

        actionBar?.setHomeButtonEnabled(true)
        actionBar?.setDisplayHomeAsUpEnabled(true)
        watermarkImageView = findViewById(R.id.watermarkImageView)
        scaleGestureDetector = ScaleGestureDetector(this, ScaleListener())
        // 设置 ImageView 的触摸监听器
        //watermarkImageView.setOnTouchListener { _, event ->
        //    scaleGestureDetector.onTouchEvent(event)
        //    true
        //}0
        var openAlbumButton = findViewById<Button>(R.id.openAlbumButton)
        openAlbumButton.setOnClickListener {
            openGallery()
        }
        var openCameraButton = findViewById<Button>(R.id.openCameraButton)
        openCameraButton.setOnClickListener {
            checkPermissionAndCamera()
        }
        var addWatermarkButton = findViewById<Button>(R.id.addWatermarkButton)
        addWatermarkButton.setOnClickListener {
            var bitmap = watermarkImageView.drawToBitmap( Bitmap.Config.ARGB_8888)
            canvas = Canvas(bitmap)
            val paint = Paint()
            paint.setStyle(Paint.Style.FILL)
            paint.setStrokeWidth(12.0F)
            paint.setTextSize(findViewById<SeekBar>(R.id.fontSizeSeekBar).progress.toFloat())
            paint.color = Color(0,0,0, findViewById<SeekBar>(R.id.opacitySeekBar).progress.toInt()).toArgb()
            val fontMetrics: Paint.FontMetrics = paint.getFontMetrics()
            val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
            val baseline: Float = distance
            paint.textAlign = Paint.Align.RIGHT
            var str = findViewById<EditText>(R.id.watermarkEditText).text.toString()
            canvas.drawText(str,0,str.length,canvas.width.toFloat(),canvas.height.toFloat()-baseline,paint)
            watermarkImageView.setImageBitmap(bitmap)
        }
        var saveAsButton = findViewById<Button>(R.id.saveImageAsButton)
        saveAsButton.setOnClickListener{
            //saveCanvasContentToPicturesDirectory(watermarkImageView.drawToBitmap( Bitmap.Config.ARGB_8888))
            saveCanvasContentToFileWithUserChoice(watermarkImageView.drawToBitmap( Bitmap.Config.ARGB_8888))
            //saveBitmap(SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())+".png",watermarkImageView.drawToBitmap( Bitmap.Config.ARGB_8888))
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId)
        {
            android.R.id.home->
            {
                this.finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_SELECT_IMAGE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode)
        {
            REQUEST_SELECT_IMAGE->
            {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    // 处理选择的图像
                    val selectedImageUri = data.data
                    watermarkImageView.setImageURI(selectedImageUri)
                    //val bitmap = Bitmap.createBitmap(watermarkImageView.width, watermarkImageView.height, Bitmap.Config.ARGB_8888)
                    //canvas = Canvas(bitmap)
                    //watermarkImageView.draw(canvas)
                }
            }
            REQUEST_CAMERA->{
                if (resultCode == RESULT_OK) {
                    if (isAndroidQ) {
                        // Android 10 使用图片uri加载
                        watermarkImageView.setImageURI(mCameraUri);
                    } else {
                        // 使用图片路径加载
                        watermarkImageView.setImageBitmap(BitmapFactory.decodeFile(mCameraImagePath));
                    }
                    //canvas = Canvas(watermarkImageView.drawToBitmap())

                } else {
                    Toast.makeText(this,"取消",Toast.LENGTH_LONG).show();
                }
            }
            REQUEST_FOLDER->{
                if (resultCode == RESULT_OK) {
                    data?.data?.let { uri ->
                        contentResolver.openOutputStream(uri)?.use { outputStream ->
                            watermarkImageView.drawToBitmap( Bitmap.Config.ARGB_8888).compress(Bitmap.CompressFormat.PNG, 100, outputStream)
                        }
                    }
                }
            }

        }
    }

    private val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012

    private fun checkPermissionAndCamera() {
        val hasCameraPermission = ContextCompat.checkSelfPermission(
            application,
            Manifest.permission.CAMERA
        )
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            //有调起相机拍照。
            openCamera()
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(
                this, arrayOf(Manifest.permission.CAMERA),
                PERMISSION_CAMERA_REQUEST_CODE
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.size > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
                //允许权限，有调起相机拍照。
                openCamera()
            } else {
                //拒绝权限，弹出提示框。
                Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show()
            }
        }
    }

    //用于保存拍照图片的uri
    private var mCameraUri: Uri? = null

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private var mCameraImagePath: String? = null

    // 是否是Android 10以上手机
    private val isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q

    /**
     * 调起相机拍照
     */
    private fun openCamera() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 判断是否有相机
        if (captureIntent.resolveActivity(packageManager) != null) {
            var photoFile: File? = null
            var photoUri: Uri? = null
            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri()
            } else {
                try {
                    photoFile = createImageFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                if (photoFile != null) {
                    mCameraImagePath = photoFile.absolutePath
                    photoUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        FileProvider.getUriForFile(
                            this,
                            "$packageName.fileprovider", photoFile
                        )
                    } else {
                        Uri.fromFile(photoFile)
                    }
                }
            }
            mCameraUri = photoUri
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                startActivityForResult(captureIntent, REQUEST_CAMERA)
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private fun createImageUri(): Uri? {
        val status = Environment.getExternalStorageState()
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        return if (status == Environment.MEDIA_MOUNTED) {
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
        } else {
            contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, ContentValues())
        }
    }
    // 保存到用户选择的路径
    fun saveCanvasContentToFileWithUserChoice(bitmap: Bitmap) {
        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "image/*"
            putExtra(Intent.EXTRA_TITLE, "canvas_content.png")
        }
        startActivityForResult(intent, REQUEST_FOLDER)
    }

    // 保存到系统的图片目录下
    fun saveCanvasContentToPicturesDirectory(bitmap: Bitmap) {
        val picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        val file = File(picturesDirectory, "canvas_content.png")
        FileOutputStream(file).use { outputStream ->
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        }
    }
    fun saveBitmap(name: String?, bm: Bitmap) {
        val savePath =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
        if (!Files.exists(Paths.get(savePath))) {
            Log.d("保存文件", "${savePath}不存在!")
        } else {
            val saveFile = File(savePath, name)
            try {
                val saveImgOut = FileOutputStream(saveFile)
                //压缩
                bm.compress(Bitmap.CompressFormat.JPEG, 90, saveImgOut)
                saveImgOut.flush()
                saveImgOut.close()
                Log.d("保存文件", "Bitmap保存至 ${saveFile.absoluteFile.toPath()}")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    /**
     * 创建保存图片的文件
     */
    @Throws(IOException::class)
    private fun createImageFile(): File? {
        val imageName: String =
            SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        if (!storageDir!!.exists()) {
            storageDir.mkdir()
        }
        val tempFile = File(storageDir, imageName)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }
    // 缩放手势监听器
    private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {
            // 获取缩放因子
            scaleFactor *= detector.scaleFactor

            // 控制缩放的范围，通常限制在一个合理的范围内
            scaleFactor = scaleFactor.coerceIn(0.1f, 10.0f)

            // 应用缩放变换到 ImageView
            watermarkImageView.scaleX = scaleFactor
            watermarkImageView.scaleY = scaleFactor

            return true
        }
    }

}